package com.globalwave.common.tree
{
	import mx.controls.Tree;
	import mx.controls.Alert;
	import mx.collections.ArrayCollection;

	public class Tree4List extends Tree
	{
		public var rootDisplayName : String ;
		public var idFieldName : String ;
		public var proIdFieldName : String ;
		public var stateFieldName : String ;
		
		public function Tree4List() {
            super();
        }

		public function buildTree(listDataProvider : Object ) : void {
		
		    var list : XML = new XML(listDataProvider) ;

		    var tree : XML = <root></root>;    
		    tree[this.labelField] = rootDisplayName ;
		    
		    var items : XML = <root></root> ;
			
		    for each (var elem :XML in list.children()) {
		    	
		    	var item : XML = <item></item> ;
		    	
		    	if (elem[stateFieldName].toString() != "") {
		    		item.@state = "checked"
		    	} else {
		    		item.@state = "unchecked"
		    	}
		    	
		    	item.@isBranch = "false" ;
		    	
		    	
		    	for each (var attrElem : XML in elem.children()) {
		    		item.@[attrElem.name().toString()] = attrElem.valueOf().toString() ;
		    	}
		    
		        items.appendChild(item) ;
		    }
		    
			
		    for (var i : int = items.children().length() - 1 ; i >=0 ; i -- ) {
		        var pro : String = items.item[i].@[proIdFieldName] ;
		        
		        if (pro == "") {
		            tree.prependChild(items.item[i]) ;            
		        } else {
		        	items.item.(@[idFieldName] == pro ).@isBranch = "true" ;
		            items.item.(@[idFieldName] == pro ).prependChild(items.item[i]) ;
		        }
		    }
		        		
		    this.dataProvider = tree ;    
						    
		}
		
		public function getSelectedIds() : ArrayCollection {
		    var ids : ArrayCollection = new ArrayCollection() ;
		    var xml : XML = new XML(this.dataProvider) ;
         	getNodeSelectedIds(xml, ids) ;
         	
         	return ids ;
		}
		
		private function getNodeSelectedIds(xml : XML , ids : ArrayCollection) :void {
        	for (var i : int = 0 ; xml != null && i < xml.children().length() ; i ++) {
        		if (xml.children()[i].@state.toString() == "checked") {
        		    ids.addItem(xml.children()[i].@[this.idFieldName].toString()) ;
        		}
        		getNodeSelectedIds(xml.children()[i], ids) ;
        	}
		}
		
	}
}